import React, { Component } from 'react';
import './data-config.css';
import { Form, Divider, Checkbox, Button, message, Select, InputNumber, Slider, Collapse } from 'antd';
import { MinusOutlined, PlusOutlined } from '@ant-design/icons';
import { connect } from 'react-redux';
import {
  addLineDao, addDepthDao, addXyDao,
  addMbLineDao, addMbDepthDao, addMbXyDao,
  setEditDepthData, getCurvesIntoDao, addNewCurveInDao, setDefaultMbInReducer, isUpdatePages,
  setChartZoom
} from '../../redux/actions';
import { reqAllMb, reqSaveDefaultMb } from '../../api';
import { getDocDataList, getDefaultMb, setDefaultMb } from '../../utils/storageUtils';
import DataTree from '../data-tree/data-tree';
import downIcon from '../../assets/image/down.png'
const { Panel } = Collapse;


const { Option } = Select;

class GlobalDataConfig extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isHaveCurve: false,
      mbList: [],
      curveNameList: [{ curve_name: "空" }],
      defaultMb: {},
      mindepth: this.props.depthDataa[0],
      maxdepth: this.props.depthDataa[this.props.depthDataa.length - 1],
      percent: this.props.gridConfig.chartZoom,
      selectState1: true,
      selectState2: true,
      selectState3: true,
      selectState4: true
    }
  }

  formRef = React.createRef();  // form对象


  onFinish1 = values => {   // 提交表单： 修改 文件深度（所有曲线）
    console.log("深度", values, this.props.daosDataList);
    if (this.props.daosDataList.length === 0) {  // 没有模板，也没有文件
      message.error("请先导入模板或文件！")
    } else {
      // 将用户输入的深度区间 处理为 以5的倍数为起点的新的 深度区间
      const mindepth = values.mindepth - (values.mindepth % 5);   // number
      const maxdepth = Math.ceil(values.maxdepth); // 向上取整显示  

      var depthInterval, oldDepth, oldCurves;   // 当前文件的深度间隔（0.1），原始文件的 深度数组  .curves[0].data
      //const oldCurves = [];   // 当前文件的 曲线数据集合
      if (getDocDataList().doc_type === "纯数据文件") {
        depthInterval = getDocDataList().interval;  // 当前文件的深度间隔0.1
        oldDepth = getDocDataList().yData;  //当前原始文件的 深度数组
        oldCurves = getDocDataList().curves;  //当前文件的 曲线数据集合
      } else if (getDocDataList().doc_type === "绘图文件") {
        depthInterval = getDocDataList().docData.interval;
        oldDepth = getDocDataList().docData.yData;
        oldCurves = getDocDataList().docData.curves;
      }
      //console.log("原始文件信息提取：",mindepth,maxdepth,depthInterval,oldDepth,oldCurves,docInfo,getDocDataList());

      var mindepthIndex, maxdepthIndex, minZeroCount, maxZeroCount;
      if (mindepth < maxdepth && maxdepth > oldDepth[0] && mindepth < oldDepth[oldDepth.length - 1]) {  // 用户 定义的 范围 合理 时，
        // 修改深度坐标
        this.props.setEditDepthData(Number(mindepth), Number(maxdepth), Number(depthInterval));

        // 找出 深度范围（新深度） 在 数组中（老深度）的位置（index区间）
        // 1.确定mindepthIndex
        if (mindepth >= Number(oldDepth[0])) {   // 新的 mindepth 一定要大于 老mindepth，才能找到对应的值
          oldDepth.forEach((item, index) => {
            if (Number(item) === mindepth) {
              mindepthIndex = index;
            }
          });
          minZeroCount = 0;
        } else {  // 新范围 超出 原始深度范围
          mindepthIndex = -1;
          minZeroCount = (oldDepth[0] - mindepth) / depthInterval; // 如果超出范围，在原数组前 需要先插值（0),计算插值总数
        }

        //2.确定maxdepthIndex
        if (maxdepth <= Number(oldDepth[oldDepth.length - 1])) {   // 新的 maxdepth 一定要小于 老maxdepth，才能找到对应的值
          oldDepth.forEach((item, index) => {
            if (Number(item) === maxdepth) {
              maxdepthIndex = index;
            }
          });
          maxZeroCount = 0;
        } else {  // 新范围 超出 原始深度范围
          maxdepthIndex = -1;
          maxZeroCount = (maxdepth - oldDepth[oldDepth.length - 1]) / depthInterval; // 如果超出范围，在原数组前 需要先插值（0),计算插值总数
        }

        //console.log("newindex",mindepthIndex,maxdepthIndex,minZeroCount,maxZeroCount)

        //截取新的curves数组
        if (mindepthIndex !== -1 && maxdepthIndex !== -1) {
          //console.log("oldcurve",oldCurves)
          oldCurves.forEach((item) => {
            item.xData = item.xData.slice(mindepthIndex, maxdepthIndex + 1);   //.xData
          })
          //console.log("oldcurve11",oldCurves);
          this.props.getCurvesIntoDao(oldCurves);  // 更新 曲线 
          return oldCurves;       //{mindepthIndex,maxdepthIndex}
        } else if (mindepthIndex === -1 && maxdepthIndex !== -1) {
          oldCurves.forEach((item) => {
            item.xData = item.xData.slice(0, maxdepthIndex + 1)
            for (let i = 0; i < minZeroCount; i++) {
              item.xData.unshift('');   // 数组前插0,(插0有漏洞，插一个'')
            }
          })
          //console.log("oldcurve12",oldCurves);
          this.props.getCurvesIntoDao(oldCurves);  // 更新 曲线 
          return oldCurves;   //{minZeroCount, maxdepthIndex}
        } else if (mindepthIndex !== -1 && maxdepthIndex === -1) {
          oldCurves.forEach((item) => {
            item.xData = item.xData.slice(mindepthIndex)
            for (let i = 0; i < maxZeroCount; i++) {
              item.xData.push('');   // 数组后插0,(插0有漏洞，插一个'')
            }
          })
          //console.log("oldcurve13",oldCurves);
          this.props.getCurvesIntoDao(oldCurves);  // 更新 曲线 
          return oldCurves;      // {mindepthIndex,maxZeroCount}
        } else if (mindepthIndex === -1 && maxdepthIndex === -1) {
          var minArr = [];
          var maxArr = [];
          for (let i = 0; i < minZeroCount; i++) {
            minArr.push('');   // 数组前插0,(插0有漏洞，插一个'')
          }
          for (let i = 0; i < maxZeroCount; i++) {
            maxArr.push('');   // 数组后插0,(插0有漏洞，插一个'')
          }
          oldCurves.forEach((item) => {
            item.xData = minArr.concat(item.xData).concat(maxArr);  // 数组拼接
          })
          //console.log("oldcurve14",oldCurves);
          this.props.getCurvesIntoDao(oldCurves);  // 更新 曲线 
          return oldCurves;   //{minZeroCount,maxZeroCount}
        }
      } else {
        message.error("深度范围设置不合理！")
      }
    }
  };

  onFinish2 = values => {   // 提交表单
    console.log("添加道", values.checkbox_group);
    values.checkbox_group.forEach((item) => {
      if (item === 'line-dao') {
        //console.log("line-dao")
        this.props.addLineDao();
        this.props.addMbLineDao();
      } else if (item === 'depth-dao') {
        //console.log("depth-dao")
        this.props.addDepthDao(100);
        this.props.addMbDepthDao(100);
      } else if (item === 'yx-dao') {
        //console.log("yx-dao")
        this.props.addXyDao();
        this.props.addMbXyDao();
      }
    });
    // this.formRef.current.resetFields();
    this.props.isUpdatePages(!this.props.updatePages);  // 及时更新页面(数据处理展示页面)

  };

  onFinish3 = values => {  // 提交表单：添加曲线
    //console.log("添加曲线：",values);
    this.setState({ isHaveCurve: false });
    var curvesCount = 0;
    if (this.props.daosDataList.length === 0) {  // 没有模板，也没有文件
      message.error("请先导入模板或文件！")
    } else {
      const data = values.curve_name;
      this.props.daosDataList.forEach((item1) => {  // 模板中曲线名唯一，不能重复
        if (item1.curves) {
          item1.curves.forEach((item2) => {
            curvesCount++;   // 统计模板中的曲线总数
            if (item2.curve_name === data) {
              message.error("模板内已存在该曲线！");
              this.setState({ isHaveCurve: true });
            }
          })
        }
      });
      //console.log("模板曲线总数：",curvesCount);
      if (!this.state.isHaveCurve) {
        var curveData, curve_id;
        var xData = [];
        if (this.props.docData.doc_type === "纯数据文件") {
          curveData = this.props.docData.curves;
        } else if (this.props.docData.doc_type === "绘图文件") {
          curveData = this.props.docData.docData.curves;
        }
        curveData.forEach((item) => {
          if (item.curve_name === data) {  // 如果文件中有该条曲线数据，则给曲线赋值
            curve_id = item.curve_id
            xData = item.xData
          }
        })
        this.props.addNewCurveInDao(data, xData, curve_id, curvesCount);  // 将新曲线添加到道中
      }
    }
    this.props.isUpdatePages(!this.props.updatePages);  // 及时更新页面(数据处理展示页面)
  }

  onFinish4 = async (values) => {  // 提交表单：设置默认模板
    const mb_id = values.mb_id;
    const user_mobile = this.props.user.user_mobile;
    const result = await reqSaveDefaultMb(user_mobile, mb_id);  // 保存用户选择的 默认模板
    console.log("保存默认模板：", result);
    if (result.code === 200) {
      const defaultMb = result.data;
      this.props.setDefaultMbInReducer(defaultMb);   // 存入 默认模板reducer
      setDefaultMb(defaultMb);
      message.success("保存成功！");
    } else {
      message.error("保存失败！");
    }
  }



  getAllMb = async () => {
    const result = await reqAllMb();
    //console.log("获取模板",result);
    if (result.code === 200) {
      const mbList = result.data;
      this.setState({
        mbList
      })
    }
  }
  //缩放增加
  increase = () => {
    let percent = this.state.percent + 10;
    if (percent > 100) {
      percent = 100;
    }
    this.setState({ percent });
    this.props.setChartZoom({ chartZoom: percent })
  };
  //缩放减少
  decline = () => {
    let percent = this.state.percent - 10;
    if (percent < 10) {
      percent = 10;
    }
    this.setState({ percent });
    this.props.setChartZoom({ chartZoom: percent })
  };
  // 拖动进度条增加或减少
  sliderChange = percent => {
    this.setState({ percent });
    this.props.setChartZoom({ chartZoom: percent })
  }


  getAllCurveNameInDoc = async (docData) => {   // 获取所有曲线名
    const curveNameList = [{ curve_name: "空" }];
    if (docData.doc_type === "纯数据文件") {
      docData.curves.map((item) => {
        if (item.type === 'curve') {
          curveNameList.push({ curve_name: item.curve_name });
        }
      })
    } else if (docData.doc_type === "绘图文件") {
      docData.docData.curves.map((item) => {
        if (item.type === 'curve') {
          curveNameList.push({ curve_name: item.curve_name });
        }
      })
    }
    this.setState({ curveNameList });
  }

  componentWillMount() {
    this.getAllMb();
    // this.getDefaultMb();   移到home中准备 默认模板 数据
  }

  componentWillReceiveProps(nextProps) {
    this.getAllCurveNameInDoc(nextProps.docData);
    this.setState({
      mindepth: nextProps.depthDataa[0],
      maxdepth: nextProps.depthDataa[nextProps.depthDataa.length - 1]
    })
  }


  render() {
    // console.log("lalal",getDefaultMb())
    const layout = {
      labelCol: { span: 13 },
      wrapperCol: { span: 10 },
    };
    const defaultMb = getDefaultMb() || {};
    const { percent } = this.state;
    return (
      <div className="global-data-config-wrapper">
        <DataTree handleReturnTop={this.props.handleReturnTop} />
        {/* <Form  
          {...layout}
          name="control-ref" 
          onFinish={this.onFinish1} 
          initialValues= {{
            "mindepth": mindepth,
            "maxdepth": maxdepth,
          }} 
        > 
          <Divider plain>显示深度</Divider>
          <Row>
            <Col span={1}></Col>
            <Col span={19}>
              <Form.Item 
                name="mindepth"
                label="起始深度(米)："
                rules={[{ required: true , message:" "}]}   
              >
                <InputNumber className="data-config-input" style={{width:95}} min={0}/>
              </Form.Item>
            </Col>
          </Row> 
          <Row>
            <Col span={1}></Col>
            <Col span={19}>
              <Form.Item
                name="maxdepth"
                label="结束深度(米)："
                rules={[{ required: true , message:"不能为空！"}]}   
              >
                <InputNumber className="data-config-input" style={{width:95}} />
              </Form.Item>
            </Col>
          </Row>      
          <Form.Item wrapperCol={{ span: 12, offset: 17 }}>
            <Button type="primary" htmlType="submit" className="global-config-button" style={{marginTop:3}}>
              确定
            </Button>
          </Form.Item> 
        </Form> */}


        <Form

          {...layout}
          name="control-ref"
          onFinish={this.onFinish6}
          initialValues={{

          }}
        >
          {/* <div className='title'>
          缩放设置
          </div> */}
          <Collapse ghost={true} expandIconPosition="right" defaultActiveKey={['1']}
            expandIcon={({ isActive }) => <div><div><img src={downIcon} alt="" style={{ transform: isActive ? 'rotate(0deg)' : 'rotate(-180deg)', transition: 'transform 0.24s', display: 'block' }}></img></div></div>}
          >
            <Panel header="缩放设置" key="1">
              <div className='optionItem'>
                <span style={{ color: '#0CC9FF' }}>图表缩放：</span>
                <Form.Item
                  name="zoom"
                >
                  {/* <Progress percent={this.state.percent} style={{width:70}}></Progress> */}
                  <Slider min={10} max={100} onChange={this.sliderChange} style={{ width: 120 }} step={10} defaultValue={percent} value={typeof percent === 'number' ? percent : 0} />
                  <InputNumber style={{ display: 'none' }} value={percent} />
                </Form.Item>
                <Button.Group>
                  <Button onClick={this.increase} className="increase" icon={<PlusOutlined />} />
                  <Button onClick={this.decline} className="decline" icon={<MinusOutlined />} />
                </Button.Group>
              </div>
            </Panel>
          </Collapse>
        </Form>
        <Divider style={{ background: 'rgba(0, 168, 246, 0.6)', minWidth: 260, width: 260, margin: '0 auto' }} />
        <Form
          {...layout}
          name="control-ref"
          onFinish={this.onFinish2}
          ref={this.formRef}
        >
          {/* <div className='title'>
            添加道
          </div> */}
          <Collapse ghost={true} expandIconPosition="right" defaultActiveKey={['1']}
            expandIcon={({ isActive }) => <div><img src={downIcon} alt="" style={{ transform: isActive ? 'rotate(0deg)' : 'rotate(-180deg)', transition: 'transform 0.24s', display: 'block' }}></img></div>}

          >
            <Panel header="添加道" key="1">
              <Form.Item name="checkbox_group" >
                <Checkbox.Group style={{ width: 260 }} className="check-box-group">
                  <div className='optionItem' style={{ padding: 0 }}>
                    <Checkbox value="line-dao" className='divider'>线性道</Checkbox>
                    <Checkbox value="depth-dao" className='divider'>深度道</Checkbox>
                    <Checkbox value="yx-dao" className='divider'>岩性道</Checkbox>
                  </div>
                </Checkbox.Group>
              </Form.Item>
              <Form.Item className='FormItemBtn' wrapperCol={{ span: 24 }}>
                <Button type="primary" htmlType="submit" className="global-config-button">
                  添加
                </Button>
              </Form.Item>
            </Panel>
          </Collapse>
        </Form>
        <Divider style={{ background: 'rgba(0, 168, 246, 0.6)', minWidth: 260, width: 260, margin: '0 auto' }} />
        <Form
          name="control-ref"
          onFinish={this.onFinish3}
        >
          <Collapse ghost={true} expandIconPosition="right" defaultActiveKey={['1']}
            expandIcon={({ isActive }) => <div><img src={downIcon} alt="" style={{ transform: isActive ? 'rotate(0deg)' : 'rotate(-180deg)', transition: 'transform 0.24s', display: 'block' }}></img></div>}
          >
            <Panel header="添加曲线" key="1">
              <Form.Item name="curve_name" label="曲线名：" rules={[{ required: true, message: "不能为空！" }]}   >
                <Select style={{ width: 191 }} placeholder="请选择" getPopupContainer={triggerNode => triggerNode.parentNode}>
                  {this.state.curveNameList.map((item, index) => <Option value={item.curve_name} key={index}>{item.curve_name}</Option>)}
                </Select>
              </Form.Item>
              <Form.Item className='FormItemBtn' wrapperCol={{ span: 24 }}>
                <Button type="primary" htmlType="submit" className="global-config-button">
                  添加
                </Button>
              </Form.Item>
            </Panel>
          </Collapse>
        </Form>
        <Divider style={{ background: 'rgba(0, 168, 246, 0.6)', minWidth: 260, width: 260, margin: '0 auto' }} />

        <Form
          ref={this.formRef}
          name="control-ref"
          onFinish={this.onFinish4}
          initialValues={{
            mb_id: defaultMb.mb_id,
          }}
        >
          {/* <div className='title'>
            默认模板
          </div> */}
          <Collapse ghost={true} expandIconPosition="right" defaultActiveKey={['1']}
            expandIcon={({ isActive }) => <div><img src={downIcon} alt="" style={{ transform: isActive ? 'rotate(0deg)' : 'rotate(-180deg)', transition: 'transform 0.24s', display: 'block' }}></img></div>}
          >
            <Panel header="默认模板" key="1">
              <Form.Item
                name="mb_id"
                label="模&nbsp;&nbsp;&nbsp;板："
                rules={[{ required: true, message: "不能为空！" }]}
              >
                <Select style={{ width: 194 }} placeholder="请选择" getPopupContainer={triggerNode => triggerNode.parentNode}>   {/*defaultValue="mb1" */}
                  {this.state.mbList.map((item, index) => <Option value={item.mb_id} key={index}>{item.mb_name}</Option>)}
                </Select>
              </Form.Item>
              <Form.Item className='FormItemBtn' wrapperCol={{ span: 24 }}>
                <Button type="primary" htmlType="submit" className="global-config-button">
                  保存
                </Button>
              </Form.Item>
            </Panel>
          </Collapse>
        </Form>
      </div>
    )
  }
}

export default connect(
  state => ({
    depthDataa: state.depthDataa, docData: state.docData, daosDataList: state.daosDataList,
    user: state.user, defaultmbData: state.defaultmbData, updatePages: state.updatePages,
    gridConfig: state.gridConfig
  }),
  {
    addLineDao, addDepthDao, addMbLineDao, addMbDepthDao, addMbXyDao,
    addXyDao, setEditDepthData, getCurvesIntoDao, addNewCurveInDao, setDefaultMbInReducer, isUpdatePages,
    setChartZoom
  }
)(GlobalDataConfig);
